package people.paper.tv.activity.home.modual.rmrb.presenter.impl;

import android.content.Context;
import android.util.Log;

import com.coocaa.app.support.net.Callback;
import com.coocaa.app.support.net.Result;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import people.paper.tv.activity.home.HomeFragment;
import people.paper.tv.activity.home.model.MainDataObject;
import people.paper.tv.activity.home.modual.rmrb.model.RMRBModel;
import people.paper.tv.activity.home.modual.rmrb.presenter.RMRBPresenter;
import people.paper.tv.activity.home.modual.rmrb.view.RMRBView;
import people.paper.tv.activity.home.modual.rmrb.view.data.DailyData;
import people.paper.tv.activity.home.modual.rmrb.view.data.DateListData;
import people.paper.tv.speech.SpeechCore;
import people.paper.tv.speech.SpeechManager;

public class RMRBPresenterImpl implements RMRBPresenter, SpeechCore.SpeechCoreListener {
    private RMRBModel model;
    private RMRBView view;
    private Context context;

    private List<MainDataObject.RMRBObject> playLists = new ArrayList<>();
    private Integer playIndex = -1;

    @Override
    public void create(Context context, RMRBView view, RMRBModel model, HomeFragment homeFragment) {
        this.context = context;
        this.view = view;
        this.model = model;
    }

    @Override
    public void start() {
        showDailyList();
        showToday();
    }

    @Override
    public void resume() {
//        synchronized (this) {
//            if (talkingObject != null)
//                SpeechManager.getSpeechManager().resume(talkingObject.talking);
//        }
    }

    @Override
    public void pause() {
        pauseTalk();
    }

    @Override
    public void onActivityStart() {
        SpeechManager.getSpeechManager().setSpeechCoreListener(this);
    }

    @Override
    public void onActivityResume() {

    }

    @Override
    public void onActivityPause() {

    }

    @Override
    public void onActivityStop() {
        SpeechManager.getSpeechManager().setSpeechCoreListener(null);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void pauseTalk() {
        synchronized (this) {
            if (talkingObject != null)
                SpeechManager.getSpeechManager().pause(talkingObject.talking);
        }
    }

    @Override
    public void reload() {
        showLayout(day);
    }

    private void showDailyList() {
        final List<RMRBModel.SupportDay> days = model.getSupportDays();
        List<DateListData> _days = new ArrayList<>();
        for (final RMRBModel.SupportDay day : days) {
            DateListData date = new DateListData();
            date.date = day.name;
            date.onClick = new Runnable() {
                @Override
                public void run() {
                    showLayout(days.indexOf(day));
                }
            };
            _days.add(date);
        }
        view.onDateLoaded(_days);
    }

    private int day = 0;

    private void showToday() {
        showLayout(0);
    }

    private void showLayout(final int day) {
        model.getPaper(day, new Callback<Result<List<MainDataObject.RMRBObject>>>() {
            @Override
            public Ret onResult(Result<List<MainDataObject.RMRBObject>> result) {
                synchronized (RMRBPresenterImpl.this) {
                    RMRBPresenterImpl.this.day = day;
                }
                if (result == null || result.exception != null) {
                    view.showError(-1);
                } else {
                    if (result != null && result.data != null) {
                        synchronized (playLists) {
                            playLists.clear();
                            int start = 0;
                            DailyData data = new DailyData();
                            data.layoutDatas = new ArrayList<>();
                            Map<String, DailyData.LayoutData> uiData = new HashMap<>();
                            for (final MainDataObject.RMRBObject object : result.data) {
                                if (data.date == null) {
                                    data.date = model.formatDate(Long.valueOf(object.date));
                                }
                                object.index = start + result.data.indexOf(object);
                                DailyData.LayoutData layoutData = uiData.get(object.layoutId);
                                if (layoutData == null) {
                                    layoutData = new DailyData.LayoutData();
                                    layoutData.index = uiData.size();
                                    layoutData.layoutId = object.layoutId;
                                    layoutData.imageUrl = object.bigPicture;
                                    layoutData.layoutTitle = object.layoutName;
                                    layoutData.thumbImageUrl = object.littlePicture;
                                    uiData.put(object.layoutId, layoutData);
                                    data.layoutDatas.add(layoutData);
                                }
                                object.indexOfLayout = layoutData.index;
                                object.indexInLayout = layoutData.reportDataList.size();
                                DailyData.ReportData reportData = new DailyData.ReportData();
                                reportData.id = object.newsId;
                                reportData.title = object.title;
                                reportData.onClick = new Runnable() {
                                    @Override
                                    public void run() {
                                        synchronized (RMRBPresenterImpl.this) {
                                            if (talkingObject == null || talkingObject != object) {
                                                talk(object.index, object);
                                            } else {
                                                if (SpeechManager.getSpeechManager().isPaused()) {
                                                    SpeechManager.getSpeechManager().resume(talkingObject.talking);
                                                } else {
                                                    SpeechManager.getSpeechManager().pause(talkingObject.talking);
                                                }
                                            }
                                        }
                                    }
                                };
                                layoutData.reportDataList.add(reportData);
                            }
                            playLists.addAll(result.data);
                            view.onDailyLoaded(data);
                        }
                    }
                }
                return new Ret(0, "success~success~success~success");
            }
        });
    }


    private synchronized void playNext() {
        synchronized (playLists) {
            synchronized (playIndex) {
                Log.d("RMRB", "playNext " + playIndex);
                if (playIndex >= 0) {
                    int _playIndex = playIndex + 1;
                    Log.d("RMRB", "_playIndex " + _playIndex + "  size:" + (playLists.size() - 1));
                    if (_playIndex < playLists.size()) {
                        MainDataObject.RMRBObject object = playLists.get(_playIndex);
                        if (talkingObject != null) {
                            if (!talkingObject.layoutId.equals(object.layoutId)) {
                                return;
                            }
                        }
                        talk(_playIndex, object);
                    }
                }
            }
        }
    }

    private MainDataObject.RMRBObject talkingObject = null;

    private void talk(final int index, final MainDataObject.RMRBObject object) {
        view.setCurPlayId(object.indexOfLayout, object.indexInLayout);
        model.getNewsContent(object.date, object.layoutId, object.newsId, new Callback<Result<String>>() {
            @Override
            public Ret onResult(Result<String> result) {
                synchronized (playIndex) {
                    playIndex = index;
                }
//                String content = "开始播放第" + index + "条";
                String content = object.title + "。" + result.data;
                synchronized (RMRBPresenterImpl.this) {
                    if (talkingObject != null)
                        SpeechManager.getSpeechManager().stop(talkingObject.talking);
                    object.talking = SpeechManager.getSpeechManager().play(content);
                    talkingObject = object;
                }
                return new Ret(0, "success~success~success~success");
            }
        });
    }

    @Override
    public void onStart(int id) {

    }

    @Override
    public void onPlaying(int id, String text, int progress) {

    }

    @Override
    public void onStop(int id) {
        synchronized (this) {
            talkingObject = null;
        }
    }

    @Override
    public void onComplete(int id) {
        playNext();
    }
}
